import { defineStore } from 'pinia'
import type { UserInfo } from '@/types/auth'
import { authService } from '@/services/auth'
import { LoginType } from '@/config'
import router from '@/router'

interface AuthState {
  userInfo: UserInfo | null
  token: string | null
  permissions: string[]
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    userInfo: null,
    token: null,
    permissions: [],
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    roles: (state) => state.userInfo?.roles || [],
    permissions: (state) => state.userInfo?.permissions || [],
  },

  actions: {
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
      this.token = userInfo.tokenInfo.tokenValue

      // 获取token过期时间，将秒转换为毫秒
      const expiresIn = (userInfo.tokenInfo.tokenTimeout || 24 * 60 * 60) * 1000 // 默认24小时，转换为毫秒
      const expiresAt = new Date().getTime() + expiresIn

      // 存储token和过期时间
      localStorage.setItem('token', userInfo.tokenInfo.tokenValue)
      localStorage.setItem('tokenExpiresAt', expiresAt.toString())
    },

    // 检查token是否过期
    isTokenExpired(): boolean {
      const expiresAt = localStorage.getItem('tokenExpiresAt')
      if (!expiresAt) return true

      return new Date().getTime() > parseInt(expiresAt)
    },

    // 从 localStorage 恢复 token
    restoreToken() {
      const token = localStorage.getItem('token')
      if (token && !this.isTokenExpired()) {
        this.token = token
      } else {
        // token过期，清除信息
        this.clearAuth()
      }
    },

    //跳转登录页面
    redirectToLogin() {
      router.push('/login')
    },

    /**
     * 获取当前登录用户信息
     */
    async fetchCurrentUser() {
      if (!this.token) return null
      const userInfo = await authService.getCurrentUser(LoginType.ADMIN)
      if (userInfo) {
        this.setUserInfo(userInfo)
        return userInfo
      }
      // 如果用户信息为空，则清除用户信息
      this.clearAuth()
      return null
    },

    clearAuth() {
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('token')
      localStorage.removeItem('tokenExpiresAt')
    },

    // 设置权限的方法
    setPermissions(permissions: string[]) {
      this.permissions = permissions
    },

    // 在登录成功后获取权限
    async fetchUserPermissions() {
      try {
        // 这里应该是你的获取权限的 API 调用
        const response = await fetch('/api/user/permissions')
        const permissions = await response.json()
        this.setPermissions(permissions)
      } catch (error) {
        console.error('获取权限失败:', error)
      }
    },
  },
})
